package com.pyl.admin.system.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.pyl.core.config.properties.ProjectProperties;
import com.pyl.core.utils.SpringContextUtil;

/**
 * 图片Controller
 * 
 * @author 潘英伦
 */

@Controller
public class PictureController {

	/**
	 * 获取图片
	 */
	@GetMapping("/picture")
	public void picture(@RequestParam(value = "p") String p, HttpServletResponse response) throws IOException {
		String defaultPath = "/images/user-picture.png";
		if (!(StringUtils.isEmpty(p) || p.equals(defaultPath))) {
			ProjectProperties properties = SpringContextUtil.getBean(ProjectProperties.class);
			String fuPath = properties.getFileUploadPath();
			String spPath = properties.getStaticPathPattern().replace("*", "");
			File file = new File(fuPath + p.replace(spPath, ""));
			if (file.exists()) {
				// 写出原文件
				FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
				return;
			}
		}
		// 写出默认文件
		Resource resource = new ClassPathResource("static" + defaultPath);
		FileCopyUtils.copy(resource.getInputStream(), response.getOutputStream());
	}
}
